dojo.provide("slipstream.view.MDEditor");
dojo.require("slipstream.layout._TemplatedLayoutWidget");
dojo.require("dijit._Container");
dojo.require("dijit.Editor");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dojox.grid.DataGrid");
dojo.require("dijit.layout.AccordionContainer");
dojo.require("dojox.form.MultiComboBox");
dojo.require("dojox.layout.ExpandoPane");
dojo.require("dojo.date.locale");
dojo.require("dijit._editor.plugins.FontChoice");
dojo.require("dijit._editor.plugins.LinkDialog");

dojo.declare("slipstream.view.MDEditor",
	[slipstream.layout._TemplatedLayoutWidget], {
		
	
	forms: null,
	slugsource: null,
	store: null,
	autosave: false,
	structure: null,
	activeItem: null,
	formConnections: null,
	widgetsInTemplate: true,
	doLayout: true,
	baseClass: "dijitContentPane",
	isDebug: true,
	prefix: '',
	suffix: '',
	uploaddir: '/images/',
	createElement: false,
	
	constructor: function(){
		this.cnx={};
		this.cnx.slugsource=new dojo.NodeList();
		this.cnx.forms=new dojo.NodeList();
		this.forms=new dojo.NodeList();
		this.slugsource=new dojo.NodeList();
		this.postLayout=new dojo.NodeList();
		this.buttons={};
	},
	/*
	postMixInProperties: function(){
		this.log('postmixin');
		this.log(this.model);
		this.log(this.tree);
		this.inherited(arguments);
	},
	*/
	postCreate: function(){
		this.log('post create');
		this.inherited(arguments);
		this.isLoaded=true;
		if (this.grid) {
			//if(this.model && !this.grid.model) this.grid.setStore(this.store);
			if(this.store && !this.grid.store) this.grid.setStore(this.store);
			dojo.connect(this.grid, 'onRowClick', this, '_onGridClick');
		}
		if(this.tree) dojo.connect(this.tree, 'onClick', this, '_onTreeClick');
		var self=this;
		if(!this.autoSave && this.buttonBar){
			this.buttons.save = new dijit.form.Button({
				label: "Spara",
				style: "float: left",
				disabled: true,
				onClick: dojo.hitch(this,function(e){
					this._forceValuesToStore();
					if(this.store.isDirty()){this.store.save()};
					console.debug(this.item);
				})
			});
			this.buttons.revert = new dijit.form.Button({
				label: "Återställ",
				disabled: true,
				onClick: dojo.hitch(this,function(e){
					this.store.revert();
					this._setItemAttr(this.item);
				})
			});
			this.buttonBar.domNode.appendChild(this.buttons.save.domNode);
			this.buttonBar.domNode.appendChild(this.buttons.revert.domNode);
			this.slugsource.attr('intermediateChanges',true);
		};
		if(this.imageButton){
			this.buttons.image=this.imageButton;
			console.debug(this.buttons.image);
			this.postLayout.push(dojo.hitch(this,function(){
				this.imageUpload=new dojox.form.FileUploader({
					uploadUrl: this.uploaddir+'UploadFile.php',
					selectMultipleFiles: false,
					button: this.buttons.image,
					isDebug: true,
					onChange: dojo.hitch(this,function(files){
						//files[0].name='staff_'+this.store.getValue(this.item,'idstaff')+files[0].type;
						//this.log('Selected files',files);
						//this.log('postdata',this.imageUpload.postData);
						var fileName=this.prefix+this.store.getValue(this.item,this.store.getIdentityAttributes()[0])+this.suffix+files[0].type;
						this.imageUpload.upload({name:(fileName)});
						//dojo.connect(this.imageUpload,'onComplete',this,'_reloadImage');
						dojo.connect(this.imageUpload,'onComplete',this,function(){
							//set name here
							this.image.src=(this.uploaddir+fileName+'?'+(new Date().toString()));
						});
						//setTimeout(dojo.hitch(this, "_reloadImage"), 200);
						//this.image.src=(this.image.src+'?'+Math.ceil(Math.random()*10000));
						//this.image.src='/images/staff_'+this.store.getValue(this.item,'idstaff')+files[0].type;
					})
				});
			}))
			/*this.imageUpload=new dojox.form.FileUploader({
				uploadUrl: '/images/UploadFile.php',
				button: this.buttons.image,
				isDebug: true
			});*/
		}
		this.buttons.create = new dijit.form.Button({
			label: "Skapa ny",
			disabled: !this.createElement,
			onClick: dojo.hitch(this,function(e){
				this._storeSaveRollback();
				this._clearForms();
				this._setItemAttr(this.store.newItem());
			})
		});
		this.buttonBar.domNode.appendChild(this.buttons.create.domNode);
		
		
	},
	
	layout: function(){
		this.log('layout');
		var cb=this._contentBox;
		if(this.getChildren().length==1){
			this.getChildren()[0].resize({h:cb.h,w:cb.w});
		} else {
			console.error('Can only contain one child, have '+this.getChildren().length,this);
		}
		this.postLayout.forEach(dojo.hitch(this,function(obj){obj()}))
	},
	_reloadImage: function(){
		this.image.src=(this.image.src+'?'+(new Date().toString()));//+Math.ceil(Math.random()*10000));
		//this.image.src=(this.uploaddir+this.image.src+'?'+(new Date().toString()));//+Math.ceil(Math.random()*10000));
		//this.imageUpload.upload({name:(this.prefix+this.store.getValue(this.item,this.store.getIdentityAttributes()[0])+this.suffix+files[0].type)});
	},
	_onGridClick: function(e){
		this.log('Grid click',e);
		//this.log('Dirty before',this.store.isDirty());
		this._storeSaveRollback();
		this.log('Index',e.rowIndex);
		var item=e.grid.getItem(e.rowIndex);
		this.log('Item',item);
		this.store.loadItem({
			item: item,
			onItem: dojo.hitch(this, "_setItemAttr"),
		});
		this.browse.toggle();
		if(!this.detail._showing) this.detail.toggle();
	},
	_onTreeClick: function(item,node){
		this.log('Tree click',item,node);
		this._storeSaveRollback();
		this._setItemAttr(item);
		this.browse.toggle();
		if(!this.detail._showing) this.detail.toggle();
		//this.log('Dirty before',this.store.isDirty());
		/*this._storeSaveRollback();
		this.store.loadItem({
			item: e.grid.getItem(e.rowIndex),
			onItem: dojo.hitch(this, "_setItemAttr"),
		});
		this.browse.toggle();
		if(!this.detail._showing) this.detail.toggle();*/
	},
	_getSlugSourceValue: function(){
		return this.slugsource.map(function(obj){return obj.attr('value')}).join(' ');
	},
	
	_clearForms: function(){
		this.cnx.slugsource.forEach(function(obj){dojo.disconnect(obj)});
		this.cnx.slugsource.length=0;
		this.cnx.forms.forEach(function(obj){dojo.disconnect(obj)});
		this.cnx.forms.length=0;
		this.forms.attr('value','');
		//this.forms.forEach(function(obj){obj.reset()})
		this.log(this.forms);
	},
	
	_setItemAttr: function(item){
		this.log('Setting item',item);
		this.log('Forms',this.forms);
		this._clearForms();
		this.item=item;
		if(this.image) this.image.src=this.uploaddir+this.prefix+this.store.getValue(item,this.store.getIdentityAttributes()[0])+this.suffix+'.jpg';
		var store=this.store;
		this.forms.forEach(dojo.hitch(this,function(obj){
			if(this.store.hasAttribute(this.item,obj.name)){
				if(store.getValue(item,obj.name)!=null){
					this.log(obj.name+': '+store.getValue(item,obj.name));
					obj.attr('value',this.store.getValue(this.item,obj.name));
				}
				this.cnx.forms.push(dojo.connect(obj,"onChange",function(){
					store.setValue(item,obj.name,obj.attr('value'));
				}));
			}
			
		}));
		if ((this.slugsource.length>0) && this.slug) {
			if ((this.slug.attr('value') == '') || (this.slug.attr('value') == convertToSlug(this._getSlugSourceValue()))) {
				this.slugsource.forEach(dojo.hitch(this,function(obj){
					this.cnx.slugsource.push(dojo.connect(obj, 'onChange', this, function(e){
						this.slug.attr('value', convertToSlug(this._getSlugSourceValue()));
					}));
				}));
			}
			this.cnx.forms.push(dojo.connect(this.slug, "onChange", this, function(){
				if (this.slug.attr('value') == '') {
					this.slug.attr('value', convertToSlug(this._getSlugSourceValue()));
					if (this.cnx.slugsource.length==0) {
						this.log(this.slugsource);
						this.slugsource.forEach(dojo.hitch(this,function(obj){
							this.cnx.slugsource.push(dojo.connect(obj,'onChange',this,function(e){
								this.slug.attr('value', convertToSlug(this._getSlugSourceValue()));
							}))
						}));
					}
				}
				else 
					if (this.slug.attr('value') != convertToSlug(this._getSlugSourceValue())) {
						dojo.forEach(this.slugConnection,function(obj){dojo.disconnect(obj)});
					}
			}))
		}
		this.buttons.save.attr('disabled',false);
		this.buttons.revert.attr('disabled',false);
	},
	
	_onChangeSlug: function(){
		if(this.slug.attr('value')=='') this.slug.attr('value',convertToSlug(this._getSlugSourceValue()));
	},
	
	_forceValuesToStore: function(){
		if (this.item) {
			dojo.forEach(this.forms, function(node){
				if(node.attr('value') instanceof Date){
					if (this.store.getValue(this.item, node.name).getTime() != node.attr('value').getTime()) {
						this.log('Changed node '+node.name);
						this.store.setValue(this.item, node.name, node.attr('value'));
					}
				} else {
					if (this.store.getValue(this.item, node.name) != node.attr('value')) {
						this.log('Changed node ',node.name,'to',node.attr('value'),'from',this.store.getValue(this.item, node.name));
						this.store.setValue(this.item, node.name, node.attr('value'));
					};
				};
			}, this);
		}
	},
	
	_storeSaveRollback: function(){
		this.log('Dirty before',this.store.isDirty());
		this._forceValuesToStore();
		this.log('Dirty after',this.store.isDirty());
		if(this.store.isDirty()){
			if(confirm('Vill du spara dina ändringar?')){
				this.store.save();
			} else {
				this.store.revert();
			}
		}
	},
	
	log: function(){
		if (this.isDebug) {
			console.log.apply(console, arguments);
		}
	},
});
